const express = require('express');
const jwt = require('jsonwebtoken');
const cors = require('cors');

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }))
app.use(cors());

const user = {
  name: 'admin',
  password: '123456'
}

// 登录接口
app.post('/api/login', (req, res) => {
  const { name, password } = req.body;
  if (name === user.name && password === user.password) {
    res.json({
      code: 200,
      msg: '登录成功',
      //签名
      token: jwt.sign({ name }, 'secret', { expiresIn: '1h' })
    });
  } else {
    res.json({
      code: 401,
      msg: '用户名或密码错误'
    });
  }
});

// 列表接口 鉴权
app.get('/api/list', (req, res) => {
  const token = req.headers.authorization.slice(7);
  jwt.verify(token, 'secret', (err, decoded) => {
    if (err) {
      res.status(403)
        .json({
          code: 403,
          msg: 'token验证失败'
        });
    } else {
      res.json({
        list: [
          { name: '1' },
          { name: '2' },
          { name: '3' },
          { name: '4' },
          { name: '5' },
          { name: '6' },
          { name: '7' },
          { name: '8' },
          { name: '9' },
          { name: '10' }
        ]
      })
    }
  })
})

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});